package com.aisile.sellergoods.service.impl;

import com.aisile.entity.PageResult;
import com.aisile.mapper.*;
import com.aisile.pojo.*;
import com.aisile.pojogroup.Goods;
import com.aisile.sellergoods.service.GoodsService;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @标题 GoodsServiceImpl
 * @作者 Mr.chen
 * @创建日期 2019/1/3 15:24
 * @版本号 1.0
 **/
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    TbGoodsMapper tbGoodsMapper;
    @Autowired
    TbGoodsDescMapper tbGoodsDescMapper;
    @Autowired
    TbItemMapper tbItemMapper;
    @Autowired
    TbBrandMapper tbBrandMapper;
    @Autowired
    TbSellerMapper tbSellerMapper;
    @Autowired
    TbItemCatMapper tbItemCatMapper;

    @Override
    public void save(Goods goods) {
        //Spu主表信息
        TbGoods goods1 = goods.getGoods();
        goods1.setAuditStatus("0");//未审核
        tbGoodsMapper.insert(goods1);
        TbGoodsDesc goodsDesc = goods.getGoodsDesc();
        goodsDesc.setGoodsId(goods1.getId());
        tbGoodsDescMapper.insert(goodsDesc);
        if("1".equals(goods1.getIsEnableSpec())){
            //Sku列表
            List<TbItem> itemList = goods.getItemList();
            for(TbItem tbItem : itemList){
                String title =  goods1.getGoodsName();; //命名规则  商品名称 + 所有规格选项
                Map<String,Object> map = JSON.parseObject(tbItem.getSpec(),Map.class);
                Set<String> keySet = map.keySet();
                for(String key:keySet){
                    title += " "+map.get(key);
                }
                tbItem.setTitle(title);// title
                setItemValues(goods,tbItem);
                tbItemMapper.insert(tbItem);
            }
        }else {
            TbItem item=new TbItem();
            item.setTitle(goods.getGoods().getGoodsName());//商品KPU+规格描述串作为SKU名称
            item.setPrice( goods.getGoods().getPrice() );//价格
            item.setStatus("1");//状态
            item.setIsDefault("1");//是否默认
            item.setNum(99999);//库存数量
            item.setSpec("{}");
            setItemValues(goods,item);
            tbItemMapper.insert(item);
        }
    }

    @Override
    public PageResult findPage(int page, int rows, TbGoods tbGoods) {
        PageHelper.startPage(page,rows);
        String auditStatus = tbGoods.getAuditStatus();
        String goodsName = tbGoods.getGoodsName();
        String sellerId = tbGoods.getSellerId();
        TbGoodsExample tbGoodsExample = new TbGoodsExample();
        if(!StringUtils.isEmpty(auditStatus)){
            tbGoodsExample.createCriteria().andAuditStatusEqualTo(auditStatus);
        }
        if(!StringUtils.isEmpty(goodsName)){
            tbGoodsExample.createCriteria().andGoodsNameLike("%"+goodsName+"%");
        }
        if(!StringUtils.isEmpty(sellerId)){
            tbGoodsExample.createCriteria().andSellerIdEqualTo(sellerId);
        }
        Page<TbGoods> goodsPage = (Page<TbGoods>)tbGoodsMapper.selectByExample(tbGoodsExample);
        return new PageResult(goodsPage.getTotal(),goodsPage.getResult());
    }

    @Override
    public Goods findOne(long id) {
        Goods goods = new Goods();
        TbGoods tbGoods = tbGoodsMapper.selectByPrimaryKey(id);
        TbGoodsDesc tbGoodsDesc = tbGoodsDescMapper.selectByPrimaryKey(id);
        //Sku 列表
        TbItemExample tbItemExample = new TbItemExample();
        tbItemExample.createCriteria().andGoodsIdEqualTo(id);
        List<TbItem> itemList = tbItemMapper.selectByExample(tbItemExample);
        goods.setGoods(tbGoods);
        goods.setGoodsDesc(tbGoodsDesc);
        goods.setItemList(itemList);
        return goods;
    }

    private void setItemValues(Goods goods,TbItem tbItem){
        TbGoods goods1 = goods.getGoods();
        tbItem.setCategoryid(goods1.getCategory3Id());
        tbItem.setGoodsId(goods1.getId());
        tbItem.setSellerId(goods1.getSellerId());
        // categoryId
        // createTime updateTime image
        // goodsId  sellerId      category brand
        tbItem.setCreateTime(new Date());//创建日期
        tbItem.setUpdateTime(new Date());//修改日期
        //品牌名称
        TbBrand brand = tbBrandMapper.selectByPrimaryKey(goods.getGoods().getBrandId());
        tbItem.setBrand(brand.getName());
        //分类名称
        TbItemCat itemCat = tbItemCatMapper.selectByPrimaryKey(goods.getGoods().getCategory3Id());
        tbItem.setCategory(itemCat.getName());
        //商家名称
        TbSeller seller = tbSellerMapper.selectByPrimaryKey(goods.getGoods().getSellerId());
        tbItem.setSeller(seller.getNickName());
        //图片地址（取spu的第一个图片）
        List<Map> imageList = JSON.parseArray(goods.getGoodsDesc().getItemImages(), Map.class) ;
        if(imageList.size()>0){
            tbItem.setImage ( (String)imageList.get(0).get("url"));
        }
    }
}
